package com.love.marriage.cloud.service.impl;

import com.aliyun.facebody20191230.models.DetectFaceAdvanceRequest;
import com.aliyun.imageaudit20191230.Client;
import com.aliyun.imageaudit20191230.models.ScanImageRequest;
import com.aliyun.tea.TeaException;
import com.google.common.collect.Lists;
import com.love.marriage.cloud.service.AliyunImageService;
import com.love.marriage.cloud.vo.AudioImageResVo;
import com.love.marriage.cloud.vo.AudioImageVo;
import com.love.marriage.config.MyAliyunConfig;
import com.love.marriage.oss.service.FileInfoService;
import com.love.marriage.oss.vo.FileInfoVo;
import com.love.marriage.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class AliyunImageServiceImpl implements AliyunImageService {

    private final MyAliyunConfig myAliyunConfig;

    private final FileInfoService fileInfoService;

    @Override
    public AudioImageResVo auditImage(AudioImageVo audioImageVo) throws Exception {
        // 审核图片
        AudioImageResVo audioImageResVo = approveImage(audioImageVo);
        if (!audioImageResVo.isApproved()) {
            return audioImageResVo;
        }
        return detectFace(audioImageVo, null);
    }

    @Override
    public AudioImageResVo auditImageFile(MultipartFile file) throws Exception {
        FileInfoVo fileInfoVo = fileInfoService.addFileInfo("common", file);
        AudioImageVo audioImageVo = new AudioImageVo();
        audioImageVo.setUrl(fileInfoVo.getPreUrl());
        // 审核图片
        AudioImageResVo audioImageResVo = approveImage(audioImageVo);
        if (!audioImageResVo.isApproved()) {
            return audioImageResVo;
        }
        return detectFace(audioImageVo, fileInfoVo);
    }

    public Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(myAliyunConfig.getAccessKeyId())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(myAliyunConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/imageaudit
        config.endpoint = myAliyunConfig.getEndpoint();
        return new Client(config);
    }

    @Override
    public AudioImageResVo approveImage(AudioImageVo audioImageVo) throws Exception {
        Client client = createClient();
        ScanImageRequest scanImageRequest = new ScanImageRequest();

        // 构建审核任务
        ScanImageRequest.ScanImageRequestTask scanImageRequestTask = new ScanImageRequest.ScanImageRequestTask();
        scanImageRequestTask.setDataId(UUID.randomUUID().toString());// 唯一任务ID
        // 根据输入类型设置图片内容（URL或Base64）
        if (StringUtils.isNotBlank(audioImageVo.getUrl())) {
            scanImageRequestTask.setImageURL(audioImageVo.getUrl());
        } else {
            throw new IllegalArgumentException("图片内容不能为空");
        }

        // 设置审核场景（根据业务需求调整）
        scanImageRequest.setScene(Arrays.asList("porn", "terrorism", "ad", "live"));
        scanImageRequest.setTask(Lists.newArrayList(scanImageRequestTask));
        AudioImageResVo resultVo = new AudioImageResVo();
//        try {
//            ScanImageResponse scanImageResponse = client.scanImageWithOptions(scanImageRequest, new RuntimeOptions());
//            log.debug("阿里云审核响应：{}", JSONObject.toJSONString(scanImageResponse));
//            if (scanImageResponse != null && scanImageResponse.getStatusCode() == 200) {
                // 解析审核结果
                boolean approved = true;
//                StringBuilder detail = new StringBuilder();
//                StringBuilder detailName = new StringBuilder();
//                List<ScanImageResponseBody.ScanImageResponseBodyDataResults> results =
//                        scanImageResponse.getBody().getData().getResults();
//                if (results.size() > 0) {
//                    for (ScanImageResponseBody.ScanImageResponseBodyDataResults res : results) {
//                        if (res.getSubResults().size() > 0) {
//                            for (ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults subRes : res.getSubResults()) {
//                                if (!"pass".equals(subRes.getSuggestion())) {
//                                    approved = false;
//                                    detail.append(subRes.getScene());
//                                    switch (subRes.getScene()) {
//                                        case "porn":
//                                            detailName.append("色情");
//                                            break;
//                                        case "terrorism":
//                                            detailName.append("暴恐");
//                                            break;
//                                        case "ad":
//                                            detailName.append("广告");
//                                            break;
//                                        case "live":
//                                            detailName.append("涉政");
//                                            break;
//                                        default:
//                                            detailName.append("违规");
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
                resultVo.setApproved(approved);
//                resultVo.setDetail(detail.length() > 0 ? detail.toString() : "图片审核通过");
//                resultVo.setDetailName(detailName.length() > 0 ? detailName.toString() : "图片审核通过");
//            } else {
//                throw new SystemException("9000011", "图片审核失败");
//            }
            return resultVo;

//        } catch (TeaException e) {
//            log.error("阿里云服务异常 (Code: {})：{}", e.getCode(), e.getMessage());
//            throw new RuntimeException("内容审核服务暂时不可用", e);
//        } catch (Exception e) {
//            log.error("系统异常：{}", e.getMessage());
//            throw new RuntimeException("图片审核处理失败", e);
//        }
    }

    public com.aliyun.facebody20191230.Client createFacebodyClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(myAliyunConfig.getAccessKeyId())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(myAliyunConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/imageaudit
        config.endpoint = myAliyunConfig.getFaceEndpoint();
        return new com.aliyun.facebody20191230.Client(config);
    }

    /**
     * 人脸检测与五官定位
     */
    public AudioImageResVo detectFace(AudioImageVo audioImageVo, FileInfoVo fileInfoVo) throws Exception {
        com.aliyun.facebody20191230.Client client = createFacebodyClient();
        DetectFaceAdvanceRequest detectFaceRequest = new DetectFaceAdvanceRequest();

        // 输入方式判断
        if (StringUtils.isNotBlank(audioImageVo.getUrl())) {
            URL url = new URL(audioImageVo.getUrl());
            InputStream inputStream = url.openConnection().getInputStream();
            detectFaceRequest.setImageURLObject(inputStream);
        } else {
            throw new IllegalArgumentException("必须提供图片URL或二进制数据");
        }

        // 设置检测参数（根据需求调整）
        detectFaceRequest.setLandmark(true);          // 返回五官关键点
        detectFaceRequest.setQuality(true);           // 返回质量信息
        detectFaceRequest.setMaxFaceNumber(3L);
        detectFaceRequest.setPose(true);
        AudioImageResVo audioImageResVo = new AudioImageResVo();
        audioImageResVo.setFileInfo(fileInfoVo);
//        try {
//            DetectFaceResponse response = client.detectFaceAdvance(detectFaceRequest, new RuntimeOptions());
//            log.debug("检测原始响应：{}", Common.toJSONString(response));
//            if (response != null && response.getStatusCode() == 200) {
//                DetectFaceResponseBody.DetectFaceResponseBodyData data = response.getBody().getData();
                boolean approved = true;
//                StringBuilder detail = new StringBuilder();
//                StringBuilder detailName = new StringBuilder();
//                if (data != null) {
//                    Integer faceCount = data.getFaceCount();
//                    if (faceCount == null || faceCount == 0) {
//                        approved = false;
//                        detail.append("faceCount").append(",");
//                        detailName.append("人脸数量不正确").append(";");
//                    }
//                    DetectFaceResponseBody.DetectFaceResponseBodyDataQualities qualities = data.getQualities();
//                    // 判断清晰度
//                    if (qualities.getBlurList() == null || qualities.getBlurList().size() == 0 || qualities.getBlurList().get(0) < 85) {
//                        approved = false;
//                        detail.append("blur").append(",");
//                        detailName.append("清晰度不正确").append(";");
//                    }
//                    // 判断人脸
//                    if (qualities.getFnfList() == null || qualities.getFnfList().size() == 0 || qualities.getFnfList().get(0) < 85) {
//                        approved = false;
//                        detail.append("fnf").append(",");
//                        detailName.append("不是人物照片").append(";");
//                    }
//                    // 判断正面照
//                    List<Float> poseList = data.getPoseList();
//                    if (!isFrontalFace(poseList)) {
//                        approved = false;
//                        detail.append("pose").append(",");
//                        detailName.append("不是正面照片").append(";");
//                    }
//                }
                audioImageResVo.setApproved(approved);
//                audioImageResVo.setDetail(detail.length() > 0 ? detail.toString() : "图片审核通过");
//                audioImageResVo.setDetailName(detailName.length() > 0 ? detailName.toString() : "图片审核通过");
//                audioImageResVo.setRequestId(response.getBody().getRequestId());
//            } else {
//                throw new SystemException("9000012", "检测失败");
//            }
//        } catch (TeaException e) {
//            handleAliyunException(e); // 统一异常处理
//            audioImageResVo.setApproved(false);
//            audioImageResVo.setDetail("请上传人物照片");
//            audioImageResVo.setDetailName("请上传人物照片");
//        }
        return audioImageResVo;
    }

    // 判断正面照的辅助方法（阈值可根据需求调整）
    private boolean isFrontalFace(List<Float> poseList) {
        if (poseList == null || poseList.size() < 3) {
            return false;
        }
        // 阈值参考：上下倾斜角Pitch、左右偏转Yaw通常要求更严格
        final float MAX_PITCH = 15.0f;  // 建议±15度以内
        final float MAX_YAW = 15.0f;    // 建议±15度以内
        final float MAX_ROLL = 30.0f;   // 平面旋转可适当放宽

        return Math.abs(poseList.get(0)) <= MAX_PITCH
                && Math.abs(poseList.get(1)) <= MAX_YAW
                && Math.abs(poseList.get(2)) <= MAX_ROLL;
    }

    // 异常处理方法
    private static void handleAliyunException(TeaException e) {
        log.error("阿里云服务错误 (Code:{}): {}", e.getCode(), e.getMessage());
        log.error("诊断建议: {}", e.getData().get("Recommend"));
    }
}
